<script setup lang="ts">
import { createAreaAPI, delAreaAPI, getAreaListAPI, updateAreaAPI } from '@/apis/area';
import { getBillingRulesListAPI } from '@/apis/billingRules';
import type { Area, AreaListParams, AreaParams } from '@/types/area';
import type { BillingRulesListData } from '@/types/billingRules';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { ref } from 'vue';


const list = ref<Area[]>([])

const params = ref<AreaListParams>({
  page: 1,
  pageSize: 10
})
const total = ref(0)
const getList = async() => {
  const res = await getAreaListAPI(params.value)
  console.log('area',res)
  list.value = res.data.rows
  total.value = res.data.total
}
getList()
// 表单初始数据
const initAddForm = () => {
  return {
    areaName: '',
    areaProportion: undefined,
    remark: '',
    ruleId: undefined,
    spaceNumber: undefined
  }
}
// 表单数据
const addForm = ref<AreaParams>(initAddForm())

const addFormRules = ref<FormRules<AreaParams>>({
  areaName: [
    { required: true, message: '请输入区域名称', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  areaProportion: [
    { required: true, message: '请输入区域面积', trigger: 'blur' },
    { pattern: /^[0-9]+.?[0-9]*$/, message:'请输入数字，包含小数', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入备注', trigger: 'blur' }
  ],
  ruleId: [
    { required: true, message: '请选择计费规则', trigger: 'blur' }
  ],
  spaceNumber: [
    { required: true, message: '请输入车位数量', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/ ,message:'请输入正整数', trigger: 'blur' }
  ]
})

const buildingDialogFlag = ref(false)
// 计费规则列表
const ruleLits = ref<BillingRulesListData[]>([])
// 打开弹窗
const onOpen = async() => {
  buildingDialogFlag.value = true
  // 获取计费规则列表
  const res = await getBillingRulesListAPI()
  console.log('rule',res)
  ruleLits.value = res.data
}
const onClose = () => {
  addForm.value = initAddForm()
  addFormRef.value?.resetFields()
  buildingDialogFlag.value = false

}

const submitLoading = ref(false)

const addFormRef = ref<FormInstance>()
const onSubmit = async() => {
  try {
    // 表单验证
    await addFormRef.value?.validate()
    submitLoading.value = true
    if(!addForm.value.id){
      await createAreaAPI(addForm.value)
      ElMessage.success('添加成功')
    }else{
      await updateAreaAPI(addForm.value)
      ElMessage.success('修改成功')
    }
    getList()
    // 关闭弹窗
    onClose()
    submitLoading.value = false
  } catch {
    submitLoading.value = false
  }
}
const delArea = async(id: number) => {
    ElMessageBox.confirm('此操作将永久删除, 是否继续?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async() => {
      await delAreaAPI(id)
      ElMessage.success('删除成功')
      getList()
    }).catch(() => {})
}
const onEdit = async(row : Area) => {
  buildingDialogFlag.value = true
  console.log('row',row)
  addForm.value = {
    areaName: row.areaName,
    areaProportion: row.areaProportion,
    remark: row.remark,
    ruleId: row.ruleId,
    spaceNumber: row.spaceNumber,
    id: row.id
  }
}
</script>

<template>
  <div class="building-container">
    <div class="create-container">
      <el-button type="primary" @click="onOpen">添加区域</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list">
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="areaName" label="区域名称" />
        <el-table-column prop="spaceNumber" label="车位数(个)" />
        <el-table-column prop="areaProportion" label="面积(m²)" />
        <el-table-column prop="ruleName" label="计费规则" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="onEdit(row)">编辑</el-button>
            <el-button size="small" type="primary" link @click="delArea(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container" style="display: flex;justify-content:end;">
      <el-pagination 
      layout="total, prev, pager, next, jumper, sizes" 
      :page-sizes="[5,10, 20, 30, 40]"
      :total="total" 
      v-model:current-page="params.page"
      v-model:page-size="params.pageSize"
      @change="getList()"
      />
    </div>
    <el-dialog :title="addForm.id ? '修改区域' : '添加区域'" width="600px" v-model="buildingDialogFlag" @close="onClose">
      {{ addForm }}
      <div class="form-container">
        <el-form label-width="100px" label-position="top" :model="addForm" :rules="addFormRules" ref="addFormRef">
          <el-form-item label="区域名称" prop="areaName">
            <el-input v-model="addForm.areaName" placeholder="请输入区域名称" />
          </el-form-item>
          <el-form-item label="车位数(个)" prop="spaceNumber">
            <el-input v-model="addForm.spaceNumber" placeholder="请输入车位数" type="number" />
          </el-form-item>
          <el-form-item label="面积"  prop="areaProportion">
            <el-input v-model="addForm.areaProportion" placeholder="请输入面积" >
              <template #append>m²</template>
            </el-input>
          </el-form-item>
          <el-form-item label="关联计费规则" prop="ruleId">
            <el-select v-model="addForm.ruleId" placeholder="请选择" clearable>
              <el-option
                v-for="item in ruleLits"
                :key="item.ruleId"
                :label="item.ruleName"
                :value="item.ruleId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input placeholder="请输入备注" v-model="addForm.remark" type="textarea"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
           <el-button size="small" @click="onClose">取 消</el-button>
           <el-button size="small" type="primary" @click="onSubmit" :loading="submitLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>